package cn.netuo.bumbersoll;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.LinearLayout;

import com.android.volley.Request;
import com.android.volley.Response;
import com.google.gson.reflect.TypeToken;
import com.rooten.frame.AppActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import cn.netuo.bumbersoll.entity.Action;
import cn.netuo.bumbersoll.entity.Cmd;
import cn.netuo.bumbersoll.entity.MqttFromS;
import cn.netuo.bumbersoll.util.BsUtil;
import lib.grasp.helper.LinearLayoutHelper;
import lib.grasp.http.BaseResponse;
import lib.grasp.http.volley.VolleyHelper;
import lib.grasp.util.AppUtil;
import lib.grasp.util.L;
import lib.grasp.util.PreferenceUtil;
import lib.grasp.util.TOAST;
import lib.grasp.widget.MessageBoxGrasp;

/**
 * 普通设置界面
 */
public class SettingActivity extends AppActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    private View mView;
    private LinearLayout mContainer;

    @Override
    protected void initView(Bundle savedInstanceState) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); //强制竖屏
        super.initView(savedInstanceState);
        mView = LayoutInflater.from(this).inflate(R.layout.activity_set, null);
        installView(mView, 1);
        init();
    }

    @Override
    protected void initActionMenu(MenuItem item) {
        super.initActionMenu(item);
        item.setVisible(false);
        setTitle("普通设置界面");
    }

    /** 初始化布局 */
    private void initView(){
        mContainer = mView.findViewById(R.id.ll_container);

        LinearLayoutHelper.addTransportSpace(this, mContainer, 20);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "业务编号", BsUtil.getBizId(this), "", "", false);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "设备编号", BsUtil.getDeviceId(this), "", "", false);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "蓝牙编号", BsUtil.getBtId(this), "", "", false);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "区域编号", BsUtil.getAreaId(this), "", "", false);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "订阅主题", BizConstant.ARG_MQTT_TOPIC, "", "", false);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "版本号", AppUtil.getAppVersionName(this) + "." + AppUtil.getAppVersionCode(this) , "", "", false);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "补丁号", BizConstant.SYS_PATCH_VERSION , "", "", false);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addSwitcheInfoLine(this, this, mContainer, "锁定前台",  BizConstant.IS_KEEP_FRONT, "111");
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addSwitcheInfoLine(this, this, mContainer, "蓝牙常开",  BizConstant.IS_BT_KEPP_ON, "01");
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "设备解绑", "与蓝牙, 二维码解除绑定关系", "", "001", true);

        LinearLayoutHelper.addTransportSpace(this, mContainer, 20);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "跳转系统桌面", "", "", "051", true);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "跳转设置界面", "", "", "052", true);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "设置无障碍", "", "", "054", true);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "申请Root权限", "", "", "055", true);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "测试静默安装", "", "", "056", true);

        LinearLayoutHelper.addTransportSpace(this, mContainer, 20);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "PWM1_ON-开", "", "", "04", true);
//        LinearLayoutHelper.addDivider(this, mContainer);
//        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "PWM1_OFF-关", "", "", "05", true);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "PWM1-频率-最亮", "", "", "06", true);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "PWM1-频率-半亮", "", "", "10", true);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "PWM1-频率-最暗", "", "", "07", true);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "(PAD1)IO1_ON", "", "", "08", true);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "(PAD1)IO1_OFF", "", "", "09", true);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "(PAD2)IO2_ON", "", "", "080", true);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "(PAD2)IO2_OFF", "", "", "090", true);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "(USB1)IO3_ON", "", "", "081", true);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "(USB1)IO3_OFF", "", "", "091", true);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "(USB2)IO4_ON", "", "", "082", true);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "(USB2)IO4_OFF", "", "", "092", true);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "蓝牙最强", "", "", "11", true);
        LinearLayoutHelper.addDivider(this, mContainer);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "蓝牙最弱", "", "", "12", true);

        LinearLayoutHelper.addTransportSpace(this, mContainer, 20);
        LinearLayoutHelper.addKeyValueArrowLine(this, this, mContainer, "跳转开发设置界面", "", "", "999", true);
    }

    @Override
    public void onClick(View v) {
        switch ((String)v.getTag()){

            case "04": {
                App.getApp().getBLEHelper().addAction(getTestCmd("PWM1_ON", "E8A101"));
                break;
            }
            case "05": {
                App.getApp().getBLEHelper().addAction(getTestCmd("PWM1_OFF", "E8A100"));
                break;
            }

            case "06": {
                App.getApp().getBLEHelper().addAction(getTestCmd("PWM1_FF", "E8A3FF"));
                break;
            }
            case "10": {
                App.getApp().getBLEHelper().addAction(getTestCmd("PWM1_88", "E8A388"));
                break;
            }
            case "07": {
                App.getApp().getBLEHelper().addAction(getTestCmd("PWM1_00", "E8A300"));
                break;
            }

            case "08": {
                App.getApp().getBLEHelper().addAction(getTestCmd("IO1_ON", "E7F101"));
                break;
            }
            case "09": {
                App.getApp().getBLEHelper().addAction(getTestCmd("IO1_OFF", "E7F100"));
                break;
            }

            case "080": {
                App.getApp().getBLEHelper().addAction(getTestCmd("IO2_ON", "E7F201"));
                break;
            }
            case "090": {
                App.getApp().getBLEHelper().addAction(getTestCmd("IO2_OFF", "E7F200"));
                break;
            }

            case "081": {
                App.getApp().getBLEHelper().addAction(getTestCmd("IO3_ON", "E7F301"));
                break;
            }
            case "091": {
                App.getApp().getBLEHelper().addAction(getTestCmd("IO3_OFF", "E7F300"));
                break;
            }

            case "082": {
                App.getApp().getBLEHelper().addAction(getTestCmd("IO4_ON", "E7F401"));
                break;
            }
            case "092": {
                App.getApp().getBLEHelper().addAction(getTestCmd("IO4_OFF", "E7F400"));
                break;
            }

            case "11": {
                App.getApp().getBLEHelper().addAction(getTestCmd("蓝牙最强", "EAC100"));
                break;
            }
            case "12": {
                App.getApp().getBLEHelper().addAction(getTestCmd("蓝牙最弱", "EAC103"));
                break;
            }
            case "001": {
                L.logOnly("设备解绑");  // 解绑成功之后提示用户重启APP
                MessageBoxGrasp.confirmMsg(this, "确定解绑? 解绑之后需要重新绑定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        doUnbind(SettingActivity.this, true);
                    }
                });
                break;
            }
            case "051": {
                Intent mHomeIntent = new Intent(Intent.ACTION_MAIN, null);
                mHomeIntent.addCategory(Intent.CATEGORY_HOME);
                ComponentName mHomecom = new ComponentName("com.android.launcher3", "com.android.launcher3.Launcher");
                mHomeIntent.setComponent(mHomecom);
                mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                startActivity(mHomeIntent);
                finish();
                break;
            }
            case "052": {
                startActivity(new Intent(Settings.ACTION_SETTINGS));
                finish();
                break;
            }
            case "054": {
                Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                startActivity(intent);
                break;
            }
            case "055": {
                L.logOnly("申请Root权限");
                new Thread(() -> AppUtil.rootCommand("123")).start();
                break;
            }
            case "056": {
                L.logOnly("AppUtil.isRoot():" + AppUtil.isRoot());
                AppUtil.installSilence(this, "/sdcard/a.apk");
                break;
            }
            case "999": {
                Intent intent = new Intent(SettingActivity.this, DevelopActivity.class);
                startActivity(intent);
                finish();
                break;
            }
        }
    }

    private void init(){
        initView();
    }

    /** 获取测试指令 */
    public static MqttFromS<Action> getTestCmd(String requestName, String target){
        MqttFromS<Action> actionMqttFromS = new MqttFromS<>();
        actionMqttFromS.requestId               = UUID.randomUUID().toString();
        actionMqttFromS.cmd                     = BizConstant.CMD_TYPE_ACT;
        actionMqttFromS.data                    = new Action();
        actionMqttFromS.data.btName             = "JDY-16";
        actionMqttFromS.data.btId               = "";
        actionMqttFromS.data.btPairPWD          = "123456";
        actionMqttFromS.data.requestName        = requestName;

        actionMqttFromS.data.cmd                = new Cmd();
        actionMqttFromS.data.cmd.serviceId      = BizConstant.DEFAULT_TARGET_BT_SERVICE_UUID;
        actionMqttFromS.data.cmd.chartId        = BizConstant.DEFAULT_TARGET_BT_CHARACTERISTICS_UUID;
        actionMqttFromS.data.cmd.targetValue    = new ArrayList<>();
        actionMqttFromS.data.cmd.targetValue.add(target);
        return actionMqttFromS;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (!buttonView.isPressed()) return;
        Object o = buttonView.getTag();
        if(!(o instanceof String)) return;
        switch ((String) o){
            case "01":{
                BizConstant.IS_BT_KEPP_ON = isChecked;
                App.getApp().getTableMgr().getTbArg().importArg(BizConstant.ARG_IS_BT_KEPP_ON_KEY, !isChecked ? "1" : "0");
                L.logOnly("蓝牙常开:" + BizConstant.IS_BT_KEPP_ON);
                break;
            }
            case "111":{
                BizConstant.IS_KEEP_FRONT = isChecked;
                App.getApp().getTableMgr().getTbArg().importArg(BizConstant.ARG_IS_KEPP_FRONT_KEY, !isChecked ? "1" : "0");
                L.logOnly("锁定前台:" + BizConstant.IS_KEEP_FRONT);
                break;
            }
            default: break;
        }
    }

    /** 解绑 */
    public static void doUnbind(Context context, boolean notify){
        String bizId = App.getApp().getTableMgr().getTbArg().queryByArgName(BizConstant.ARG_BIZ_ID_KEY);

        Map<String, String> map = new HashMap<>();
        map.put("id"        , bizId);

        VolleyHelper.with(context)
                .setURL(BizConstant.GET_UNBIND)
                .setMethod(Request.Method.GET)
                .setHeadParam(new HashMap<>())
                .setParam(map)
                .setIsShowProg(true, "正在解绑")
                .setSwip(null)
                .onSuccess((Response.Listener<BaseResponse>) response -> {
                    if (response == null || response.code != 0) {
                        TOAST.showShort(context, "解绑失败" + ((response != null && !TextUtils.isEmpty(response.msg)) ? "," + response.msg : ""));
                        return;
                    }
                    L.logOnly("解绑-成功");

                    PreferenceUtil.saveSerializableEntity(context, BizConstant.OFF_USB_TASK_KEY, null);
                    if(notify) MessageBoxGrasp.infoMsg(context, "解绑完成", "请重新启动App", false, v -> doStopApp());
                    else doStopApp();
                })
                .onError(volleyError -> TOAST.showShort(context, "解绑失败"))
                .execute(new TypeToken<BaseResponse>() {
                }.getType());
    }

    /** 主动关闭App */
    public static void doStopApp(){
        App.getApp().stopAppOnService();
        App.getApp().getTableMgr().dropDB();
        App.getApp().destroyApp(true);
    }
}
